package org.sepheriel.airy2d.shader;

import org.lwjgl.opengl.GL11;
import java.io.BufferedReader;
import java.io.FileReader;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.ARBShaderObjects;
import org.lwjgl.opengl.ARBVertexShader;
import org.lwjgl.opengl.ARBFragmentShader;
import org.lwjgl.opengl.Util;
import org.sepheriel.airy2d.math.Vec2;


public class ShaderObj {
	
	private boolean useShader = true;
	
	private int shader = 0;
	private int vertShader = 0;
	private int fragShader = 0;
	
	public ShaderObj() {
		
		shader = ARBShaderObjects.glCreateProgramObjectARB();
		
		if(shader != 0) {
			vertShader = createVertShader("shader/screen.vert");
			fragShader = createFragShader("shader/screen.frag");
		} else {
			useShader = false;
		}
		
		if(vertShader != 0 && fragShader != 0) {
			ARBShaderObjects.glAttachObjectARB(shader, vertShader);
			ARBShaderObjects.glAttachObjectARB(shader, fragShader);
			ARBShaderObjects.glLinkProgramARB(shader);
			ARBShaderObjects.glValidateProgramARB(shader);
			
		} else {
			useShader = false;
		}
	}
		
		public void draw() {
			
			if(useShader) {
				ARBShaderObjects.glUseProgramObjectARB(shader);
			}

				GL11.glBegin(GL11.GL_QUADS);
					GL11.glVertex2f(0f, 0f);
					GL11.glVertex2f(100f, 0f);
					GL11.glVertex2f(100f, 100f);
					GL11.glVertex2f(0f, 100f);
				GL11.glEnd();
				
				ARBShaderObjects.glUseProgramObjectARB(0);
			}
		
		
		private int createVertShader(String filename) {

			vertShader=ARBShaderObjects.glCreateShaderObjectARB(ARBVertexShader.GL_VERTEX_SHADER_ARB);

		if(vertShader==0){return 0;}
			String vertexCode="";
			String line;
		try{
			BufferedReader reader=new BufferedReader(new FileReader(filename));
				while((line=reader.readLine())!=null){
					vertexCode+=line + "\n";
				}
			}catch(Exception e){
				System.out.println("Fail reading vertex shading code");
				return 0;
			}

			ARBShaderObjects.glShaderSourceARB(vertShader, vertexCode);
			ARBShaderObjects.glCompileShaderARB(vertShader);
			
			return vertShader;
		}
		

		private int createFragShader(String filename){
			
			fragShader=ARBShaderObjects.glCreateShaderObjectARB(ARBFragmentShader.GL_FRAGMENT_SHADER_ARB);
			
		if(fragShader==0){return 0;}
			String fragCode="";
			String line;
		try{
			BufferedReader reader=new BufferedReader(new FileReader(filename));
				while((line=reader.readLine())!=null){
					fragCode+=line + "\n";
				}
		}catch(Exception e){
			System.out.println("Fail reading fragment shading code");
			return 0;
		}
			ARBShaderObjects.glShaderSourceARB(fragShader, fragCode);
			ARBShaderObjects.glCompileShaderARB(fragShader);

			return fragShader;
		}
		
	}
